package sardine.exception;

import java.util.HashMap;
import java.util.Map;

/**
 * @auth bruce-sha
 * @date 2015/5/21
 */
public class ExceptionMapper {

    private Map<Class<? extends Exception>, ExceptionHandler> exceptionMap;

    public ExceptionMapper() {
        this.exceptionMap = new HashMap<>();
    }


    private static ExceptionMapper defaultInstance;

    public static ExceptionMapper singleton() {
        if (defaultInstance == null) defaultInstance = new ExceptionMapper();
        return defaultInstance;
    }


    /**
     * Maps the given handler to the provided exception type. If a handler was already registered to the same type, the
     * handler is overwritten.
     *
     * @param exceptionClass Type of exception
     * @param handler        Handler to map to exception
     */
    public void map(Class<? extends Exception> exceptionClass, ExceptionHandler handler) {
        this.exceptionMap.put(exceptionClass, handler);
    }

    /**
     * Returns the handler associated with the provided exception class
     *
     * @param exceptionClass Type of exception
     * @return Associated handler
     */
    public ExceptionHandler getHandler(Class<? extends Exception> exceptionClass) {
        // If the exception map does not contain the provided exception class, it might
        // still be that a superclass of the exception class is.
        if (!this.exceptionMap.containsKey(exceptionClass)) {

            Class<?> superclass = exceptionClass.getSuperclass();
            do {
                // Is the superclass mapped?
                if (this.exceptionMap.containsKey(superclass)) {
                    // Use the handler for the mapped superclass, and cache handler
                    // for this exception class
                    ExceptionHandler handler = this.exceptionMap.get(superclass);
                    this.exceptionMap.put(exceptionClass, handler);
                    return handler;
                }

                // Iteratively walk through the exception class's superclasses
                superclass = superclass.getSuperclass();
            } while (superclass != null);

            // No handler found either for the superclasses of the exception class
            // We cache the null value to prevent future
            this.exceptionMap.put(exceptionClass, null);
            return null;
        }

        // Direct map
        return this.exceptionMap.get(exceptionClass);
    }

    public ExceptionHandler getHandler(Exception exception) {
        return this.getHandler(exception.getClass());
    }
}
